import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/primeng';
import { DictService } from './service/dict.service';

@Component({
  templateUrl: './dict-detail.component.html',
  styleUrls: ['./dict-detail.component.scss'],
  providers: [DictService]
})
export class DictDetailComponent implements OnInit {
  dictId: number;
  sysId: number;
  dictKey: string;
  dictForm: FormGroup;
  dict: any = {};
  dictItems: any[];
  cols: any[] = [
    { field: 'seq', header: '序号', width: '120px' },
    { field: 'dictItemName', header: '标签' },
    { field: 'dictItemValue', header: '键值' },
    { field: 'displayOrder', header: '排序', width: '120px' }
  ];

  constructor(
    private fb: FormBuilder,
    private dictService: DictService,
    private ref: DynamicDialogRef,
    private config: DynamicDialogConfig) {
    this.dictId = this.config.data.dictId || 0;
    this.sysId = this.config.data.sysId;
  }

  ngOnInit(): void {
    this.dictService.loadDictDetails(this.dictId).subscribe(dict => {
      this.dict = dict;
      this.dictItems = dict.items
      this.dictItems.forEach((ele, i) => ele["seq"] = (i + 1))
      this.buildForm();
    })
    this.buildForm();
  }

  buildForm(): void {
    this.dictForm = this.fb.group({
      'dictId': [this.dict.dictId],
      'sysId': [this.dict.sysId],
      'dictName': [this.dict.dictName, [
        Validators.required,
        Validators.maxLength(20)
      ]
      ],
      'dictKey': [this.dict.dictKey, [
        Validators.required,
        Validators.minLength(3),
        Validators.maxLength(20),
        Validators.pattern('[A-Z|_]*$')
      ]
      ],
      'dictDesc': [this.dict.dictDesc]
    });

    this.dictForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
  }
  /**保存接口*/
  save() {
    let formValue = this.dictForm.value;
    formValue['sysId'] = this.sysId;
    formValue["items"] = this.dictItems;
    this.dictService.saveUpdate(formValue).subscribe(data => {
      this.ref.close(data);
    });
  }
  onValueChanged(data?: any) {
    if (!this.dictForm) { return; }
    const form = this.dictForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**取消 */
  cancel() {
    this.ref.close();
  }

  /**删除字典栏目 */
  deleteItem(item: any) {
    var temp = [];
    this.dictItems.forEach(element => {
      if (element.dictItemValue != item.dictItemValue)
        temp.push(element);
    });
    this.dictItems = temp;
  }

  /**添加字典项 */
  addItem($event: any) {
    this.dictItems.push({ 'seq': this.dictItems.length + 1, 'displayOrder': this.dictItems.length + 1 });
  }
  formErrors = {
    'dictName': '',
    'dictKey': ''
  };


  validationMessages = {
    'dictName': {
      'required': '字典名称为必填项',
      'maxlength': '字典名称长度不能超过20个字符'
    },
    'dictKey': {
      'required': '字典键值不能为空',
      'minlength': '字典键值长度必须在3到20个字符之间',
      'maxlength': '字典键值长度必须在4到20个字符之间',
      'pattern': '字典键值只能包含大写字母和下划线'
    }
  };

}
